package com.ht.api.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.Entity;
import com.ht.api.db.StreamLoadConfig;
import com.ht.api.db.util.HtUtil;
import com.ht.api.util.NoticeUtil;
import com.ht.api.util.RuleSqlUtil;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;

/**
 * 标签
 */
@Slf4j
public class TagService {

    public static void refreshTag(DataSource ds, StreamLoadConfig config, Entity tag) {
        String tagCode = tag.getStr("tag_code");

        // 根据规则生成满足规则的sql
        JSONObject rules = tag.getJSONObject("rules");
        List<Object> params = new ArrayList<>();
        String conditionSql = RuleSqlUtil.buildConditionSql(rules, params);


        // 根据规则sql，创建查询标签变化的对象的sql
        StringBuilder sql = StrUtil.builder();
        sql.append("select bitmap_to_string(bitmap_not(tids.id, normalids.id)) as inids, bitmap_to_string(bitmap_not(normalids.id, tids.id)) as outids ");
        sql.append("from ");
        sql.append("(").append(conditionSql).append(") tids, ");
        sql.append("(select bitmap_union(to_bitmap(relation_id)) id from tag_relation where tag_id = " + tag.getMainId() + " and status = 0 and tag_code = '"+tagCode+"') normalids ");

        DbList tagUsers = Db.query(ds, sql.toString(), params);

        String inids = tagUsers.get(0).getStr("inids"); // 新的满足标签的对象
        String outids = tagUsers.get(0).getStr("outids"); // 当前需要退出正常标签状态的对象

        List<Entity> datalist = new ArrayList<>();
        String eventTime = DateUtil.now();
        if (StrUtil.isNotBlank(inids)) {
            for (String id : inids.split(",")) {
                Entity tagRelationLogs = Entity.create("tag_relation_logs");
                tagRelationLogs.set("relation_id", id);
                tagRelationLogs.set("tag_id", tag.getMainId());
                tagRelationLogs.set("tag_code", tag.get("tag_code"));
                tagRelationLogs.set("status", 0);
                tagRelationLogs.set("time", eventTime);
                tagRelationLogs.set("tag_group_id", tag.get("tag_group_id"));

                datalist.add(tagRelationLogs);
            }
        }

        if (StrUtil.isNotBlank(outids)) {
            for (String id : outids.split(",")) {
                Entity tagRelationLogs = Entity.create("tag_relation_logs");
                tagRelationLogs.set("relation_id", id);
                tagRelationLogs.set("tag_id", tag.getMainId());
                tagRelationLogs.set("tag_code", tag.get("tag_code"));
                tagRelationLogs.set("status", -1);
                tagRelationLogs.set("time", eventTime);
                tagRelationLogs.set("tag_group_id", tag.get("tag_group_id"));

                datalist.add(tagRelationLogs);
            }
        }

        Db.insertBatchWithStream(config, datalist);

        if (datalist.size() > 0) {//保存日志
            HtUtil.createLog(ds, tag.getMainId(), StrUtil.format("标签刷新数据：新增客户数-> %s，退出客户数-> %s",
                    StrUtil.isBlank(inids) ? 0 : inids.split(",").length, StrUtil.isBlank(outids) ? 0 : outids.split(",").length));
        }
    }
}
